package com.efruit.shopcart;

import java.util.Collection;
import java.util.HashMap;

public class ShoppingList {
	private HashMap<Integer, ShoppingItem> items;
	
	public ShoppingList(){
		items = new HashMap<Integer, ShoppingItem>();
	}

	public ShoppingItem addProduct(IProductInfo productInfo) {
		int id = productInfo.getId();
		ShoppingItem item = items.get(id);
		if (item == null) {
			item = new ShoppingItem(productInfo, 1);
			items.put(id, item);
		} else {
			item.setAmount(item.getAmount() + 1);
		}
		return item;
	}

	public ShoppingItem removeProduct(int id) {
		return items.remove(id);
	}

	/**
	 * @param id
	 *            the id of product
	 * @param amount
	 *            the amount of product; the product will be removed from the
	 *            shopping list if the amount equals 0
	 * @return null if product with the certain id is not in the shopping list
	 *         or the amount value is illegal
	 */
	public ShoppingItem setProductAmount(int id, int amount) {
		if (amount == 0) {
			return removeProduct(id);
		}
		ShoppingItem item = items.get(id);
		if (item == null) {
			System.err.println("item does not exist. could not set amount");
			return null;
		}
		ShoppingItem temp = new ShoppingItem(item);
		if(item.setAmount(amount))
			return temp;
		else
			return null;
	}

	public Collection<ShoppingItem> getShoppingInfo() {
		return items.values();
	}

}
